"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

from threading import Timer
from msnp.logger import Logger
from msnp.persistence import PersistenceController, FileAccessor, XMLController
from msnp.model import MediaModel, PTPModel
from msnp.gui import MySignal
from msnp.service.synch.timer import SynchChangesTimer

__rescanTimer = None
__synchChangeSize = 0
__timerRound = 1
__shouldRestart = True

def __restartTimer():
    """This function restarts a Timer object if __shouldRestart is True."""
    global __rescanTimer
    global __shouldRestart
    
    if __shouldRestart:
        #assumption: if amarok starts scan, every 2 seconds a change in the db happens
        __rescanTimer = Timer(2, __executeRescanTimer)
        __rescanTimer.start()
    
def startTimer():
    """This function initially starts a Timer object.
    
    The Timer object calls the __executeRescanTimer function after 2 seconds.
    This function is called when Amarok is restarted to wait until Amarok rescanned the whole collection.
    """
    global __synchChangeSize
    global __timerRound
    global __shouldRestart
    __synchChangeSize = 0
    __timerRound = 1
    __shouldRestart = True
    filepath = XMLController.readAllSettings().getCurrentUserSettings().getAmarokConfFilePath()
    FileAccessor.overwriteFile(filepath, MediaModel.RescanStatus.START_SYNCH)
    __restartTimer()

def stopTimer():
    """This function stops the Timer object if running."""
    global __shouldRestart
    global __rescanTimer
    
    __shouldRestart = False
    if __rescanTimer != None:
        __rescanTimer.cancel()
    
def __executeRescanTimer():
    """This function is called by the Timer object.
    
    It either restarts the Timer to wait for the ongoing synchronization process,
    or, if this finished already, it deletes the SynchChanges table of the media database
    and starts the SynchChangesTimer again.
    """
    global __rescanTimer
    global __synchChangeSize
    global __timerRound
    
    Logger.info("Rescan Timer running")
    size = PersistenceController.selectSynchChangesSize()
    userSettings = XMLController.readAllSettings().getCurrentUserSettings()
    confFileContent = FileAccessor.readFromFile(userSettings.getAmarokConfFilePath())
    #after 20 seconds (10 rounds) without executing the amarok script we must suppose that the script 
    #is not installed or amarok hasn't been restarted
    continueTimer = confFileContent == MediaModel.RescanStatus.START_SYNCH and __timerRound < 10
    
    #if there are changes in the synch_changes table we surely restart this timer
    if size > __synchChangeSize or continueTimer:
        __synchChangeSize = size
        __timerRound += 1
        __restartTimer()
    else:
        #delete all synch changes
        PersistenceController.deleteSynchChanges()
        #start timer again
        SynchChangesTimer.startSynchChangesTimer()
        #enable synchronization
        MySignal.emitSynchEnableSignal(True, True, PTPModel.ReturnType.SUCCESSFUL)
